package com.example.demo.serviceImpl;

import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.Result;
import com.example.demo.vo.PageBean;
import com.example.demo.vo.userVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.demo.utils.tokenUtil.getToken;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper usermapper;

    @Override
    public Result Login(userVo user){
        System.err.println(user);
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        List<userVo> uesrInfo = usermapper.Login(user);
        if(uesrInfo.size() > 0){
            String token = getToken(uesrInfo.get(0));
            Map map=new HashMap();
            map.put("token",token);
            map.put("info",uesrInfo.get(0));
            return Result.success(map);
        }else {
            return Result.failure(-1,"用户名或密码错误");
        }
    }

    @Override
    public Result register(userVo user){
        int existence = usermapper.getUserbyusername(user);
        if(existence > 0){
            return Result.failure(-1,"用户已存在!");
        }
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        int type = usermapper.register(user);
        System.err.println(type);
        if(type == 1){
            return Result.success();
        }else {
            return Result.failure(-1,"注册失败");
        }

    }

    @Override
    public Result getlist(String username,Integer id ,int currentPage,int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<userVo> itemsList = usermapper.findItem(username,id); //查询商品
        PageInfo info=new PageInfo(itemsList);//1、PageInfo 是 pagehelper中内值的分页的信息类
        int num = (int) info.getTotal();
        PageBean<userVo> pageData = new PageBean<>(currentPage, pageSize, num);
        pageData.setRows(itemsList);
        return Result.success(pageData);
    }

    @Override
    public Result del(int id) {
        int i = usermapper.del(id);
        if(i == 0){
            return Result.failure(-1,"操作失败");
        }else {
            return Result.success();
        }
    }

    @Override
    public Result update(userVo uservo) {
        int i = usermapper.update(uservo);
        if(i == 0){
            return Result.failure(-1,"操作失败");
        }else {
            return Result.success();
        }
    }

    @Override
    public userVo findUserById(int parseInt) {
        return usermapper.findUserById(parseInt);
    }
}
